package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        //将employeedto转成employee对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        LocalDateTime now = LocalDateTime.now();
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //employee.setCreateTime(now);
        //employee.setUpdateTime(now);       公共字段注入，使用切面编程的思想
        //动态获取登陆人的id
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.addEmployee(employee);
    }

    @Override
    public PageResult getEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        //PageHelper
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> empPage = employeeMapper.getAll(employeePageQueryDTO.getName());
        long l = empPage.getTotal();
        List<Employee> result = empPage.getResult();
        return new PageResult(l,result);

    }

    @Override
    public void setStatus(String status, String id) {
        Integer sts=Integer.parseInt(status);
        Integer empid=Integer.parseInt(id);
        Integer updateUser= Math.toIntExact(BaseContext.getCurrentId());
        LocalDateTime  now = LocalDateTime.now();
        employeeMapper.updateStatus(sts,empid,now,updateUser);
    }

    @Override
    public void setEmpInfo(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //将otd拷贝到一个新的emp对象
        BeanUtils.copyProperties(employeeDTO,employee);
        LocalDateTime now = LocalDateTime.now();
        //employee.setCreateTime(now);
        //employee.setUpdateTime(now);    同添加员工的方法
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());
        //全局异常中会判断username字段是否重复，不需要再写sql语句判断
        //在编辑之前，要先判断username是否修改，如果修改，看是否符合唯一约束
        /*String username = employee.getUsername();
        Employee byUsername = employeeMapper.getByUsername(username);
        if (byUsername != null &&!(byUsername.getUsername().equals(employee.getUsername()))) {
            //账号已被注册，无法修改
            throw new BaseException(username+"已被使用，修改失败");
        }else {*/
            employeeMapper.updateEmployee(employee);
        //}

    }

    @Override
    public void changePassword(PasswordEditDTO passwordEditDTO) {
        //首先确定密码正不正确
        Long empId1 = BaseContext.getCurrentId();
        passwordEditDTO.setEmpId(empId1);
        Employee employee = employeeMapper.getById(empId1.intValue());
        //密码判断
        if (!(employee.getPassword().equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes())))) {
            //老密码错误
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }
        //老密码正确
        //将新密码通过md5加密存入数据库
        String s = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        passwordEditDTO.setNewPassword(s);
        Integer updateUser= Math.toIntExact(BaseContext.getCurrentId());
        LocalDateTime  now = LocalDateTime.now();
        employeeMapper.updatePassword(passwordEditDTO,now,updateUser);
    }
}

